//
//  OAuthViewController.swift
//  XiaozhuangWeibo
//
//  Created by Maxwell on 11/19/18.
//  Copyright © 2018 Maxwell. All rights reserved.
//

import UIKit
import WebKit
import Alamofire
import SwiftyJSON

class OAuthViewController: UIViewController,WKNavigationDelegate {

    let weibo_url = "https://api.weibo.com/oauth2/authorize"
    let deli_app_key = "1074546594"
    
    let deli_app_secret = "d73b72abd0fe1079bcd943775bf5c434"
    let redirect_uri = "https://www.baidu.com"
    let codeEqual = "code="
    let request_url = "https://api.weibo.com/oauth2/access_token"
    let home_timeline_url = "https://api.weibo.com/2/statuses/home_timeline.json"
    
    var token_code = ""
    var access_token = ""
    var account:UserAccount?
    
    var weiboHomeDatas = [WeiboData]()
    
    lazy var loginWKWebView:WKWebView = {
        let loginWKV = WKWebView()
        loginWKV.frame = CGRect(x: 0, y: 20, width: view.bounds.width, height: view.bounds.height-20)
        return loginWKV
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(loginWKWebView)
        let url_str = "\(weibo_url)?client_id=\(deli_app_key)&redirect_uri=\(redirect_uri)"
        let url = URL(string: url_str)
        let request = URLRequest(url: url!)
        loginWKWebView.load(request)
        navigationItem.title = "晓庄微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(closeLogin))
        
        loginWKWebView.navigationDelegate = self
    }
    
    @objc func closeLogin(){
        dismiss(animated: true, completion: nil)
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        /*
         1.页面加载完成
         https://api.weibo.com/oauth2/authorize?client_id=1074546594&redirect_uri=https://www.baidu.com
         2.跳转成功
         https://api.weibo.com/oauth2/authorize
 
         3-1.点击授权成功
         https://www.baidu.com/?code=80969634cb1d388ebf5f240444d8de9c
 
         3-2 取消授权
         https://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
 */
        
        if let return_str = webView.url{
            let url = return_str.absoluteString
            if url.hasPrefix(redirect_uri) {
                if let queryStr = return_str.query{
                    let index = queryStr.index(queryStr.startIndex, offsetBy: codeEqual.count)
                    token_code =  String(queryStr[index..<queryStr.endIndex])
                    //测试令牌是否正确
                    //print(token_code as Any)
                    self.dismiss(animated: true, completion: load_request)
                    //load_request()
                }
            }
        }
    }
    func load_request(){
        let canshu = [  "client_id":"\(deli_app_key)",
                        "client_secret":"\(deli_app_secret)",
                        "grant_type":"authorization_code",
                        "code":"\(token_code)",
                        "redirect_uri":"\(redirect_uri)"]
        
        Alamofire.request(request_url, method: .post, parameters: canshu, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            
                switch response.result.isSuccess {
                    case true:
                        if let value = response.result.value {
                            let json = JSON(value)
                    
                            let user = UserAccount.init(jsonData: json)
                            self.access_token = user.access_token!
                            //通知切换视图
                            NotificationCenter.default.post(name: NSNotification.Name("qiehuanshitu"), object: self, userInfo: ["access_token":"\(user.access_token!)"])
                            //self.accessUserHomepage()
                            
                        }
                    case false:
                        print(response.result.error!)
            }
        }
    }
    //value = "2.00I_8NYBgegiKB12dbf5f9fcTruN8C"
    func accessUserHomepage(){
        let canshu = ["access_token":"\(access_token)"]
        Alamofire.request(home_timeline_url, method: .get, parameters: canshu, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            switch response.result.isSuccess {
                case true:
                    if let value = response.result.value {
                        let json = JSON(value)
                        //let weibo1 = json["statuses"][0]
                            
                        //1.存储到模型
                        self.weiboHomeDatas = self.saveWeiboHome(jsondata:json)
                        print("成功地获取用户首页，用户首页的数据是：\(String(describing: self.weiboHomeDatas[0].text))")
                    }
                    case false:
                        print(response.result.error!)
            }
        }
       
    }
    
    func saveWeiboHome(jsondata:JSON) -> [WeiboData]{
        var weiboshouye = [WeiboData]()
        for i in 0..<jsondata["statuses"].count {
            let weibo1 = WeiboData(jsonData: jsondata["statuses"][i])
            weiboshouye.append(weibo1)
        }
        return weiboshouye
    }
}
/*
 
 https://api.weibo.com/oauth2/authorize?client_id=1074546594&redirect_uri=https://www.baidu.com
 https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.00I_8NYBgegiKB12dbf5f9fcTruN8C
 */
